﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using AuditModel;
using AuditWeb.Models;
using System.IO;
using System.Reflection;
using System.Drawing;
using DoddleReport.Web;
using DoddleReport;
using System.Globalization;

namespace AuditWeb.Controllers
{
    [Authorize(Roles = "学科组组长")]
    public class SubjectAdminController : Controller
    {
        AuditDBEntities db = new AuditDBEntities();
        IAnnualEventBL iaebl = new AnnualEventBL();
        IScoreBL isbl = new ScoreBL();
        IArchiveBL iabl = new ArchiveBL();
        ICandidateQuotaBL icqbl = new CandidateQuotaBL();
        
        //
        // GET: /SubjectAdmin/

        public ActionResult Index()
        {
            int _subjectid = (int)HttpContext.Profile["SubjectId"];
            AnnualEvent currentevent = iaebl.GetActiveEvents().FirstOrDefault();
            string annualeventid = currentevent.ID;
            ViewBag.AnnualEvent = currentevent;
            ViewBag.AnnualEventId = annualeventid;
            ViewBag.SubjectName = db.Subjects.SingleOrDefault(s => s.Id == _subjectid).Name;

            var archives = from a in db.Archives where a.SubjectID == _subjectid select a;
            ViewBag.ArchivesCount = archives.Count();

            var scores = isbl.GetEventSubjectScores(currentevent.ID, _subjectid);
            ViewBag.ScoreCount = scores.Count();

            var ClassDates = (from a in archives select new PWCountyClassDate() { CountyName = a.County.Name, ClassDate = a.ClassDate.Value, CountyCode = a.CountyCode }).Distinct();
            ViewBag.ClassDateList = ClassDates.ToList();

            var countycqlist = icqbl.GetCandidateQuotasTotal(currentevent.ID, _subjectid, "");
            int CandidateQuotaCount = (from cq in countycqlist select cq).Sum(cq => cq.Quota).Value;

            ViewBag.CandidateQuotaCount = CandidateQuotaCount;

            return View();
        }

        public ViewResult CandidateQuota()
        {
            //ViewBag.ActiveAnnualEvents = new SelectList(aebl.GetActiveEvents(), "Id", "Title");
            //string eventid = aebl.GetActiveEvents().First().ID;

            //return RedirectToAction("Index", "Archive", new { id = eventid });
            AnnualEvent currentevent = iaebl.GetActiveEvents().FirstOrDefault();
            ViewBag.AnnualEvent = currentevent;
            ViewBag.AnnualEventId = currentevent.ID;
            int _subjectid = (int)HttpContext.Profile["SubjectId"];


            ViewBag.SubjectName = db.Subjects.SingleOrDefault(s => s.Id == _subjectid).Name;
            var cqlist = icqbl.GetCandidateQuotasTotal(currentevent.ID, _subjectid, "");

            return View(cqlist);
        }

        [Authorize(Roles = "学科组组长")]
        public ViewResult ArchiveDetails(string id)
        {
            Archive archive = db.Archives.Single(a => a.ID == id);
            int _subjectid = (int)HttpContext.Profile["SubjectId"];
            ViewBag.AnnualEvent = iaebl.GetAnnualEvent(archive.AnnualEventID);
            ViewBag.AnnualEventId = archive.AnnualEventID;
            ViewBag.CountyName = db.Counties.SingleOrDefault(c => c.Code == archive.CountyCode).Name;
            ViewBag.SubjectName = db.Subjects.SingleOrDefault(s => s.Id == _subjectid).Name;
            return View(archive);
        }

        public ActionResult ExpertJudges()
        {
            int _subjectid = (int)HttpContext.Profile["SubjectId"];
            AnnualEvent currentevent = iaebl.GetActiveEvents().FirstOrDefault();
            string annualeventid = currentevent.ID;
            ViewBag.AnnualEvent = currentevent;
            ViewBag.AnnualEventId = annualeventid;
            ViewBag.SubjectName = db.Subjects.SingleOrDefault(s => s.Id == _subjectid).Name;

            return View((from ej in db.ExpertJudges where ej.SubjectID==_subjectid select ej).ToList());
        }

        public ReportResult ExportToExcel()
        {
         //prepare params
            int _subjectid = (int)HttpContext.Profile["SubjectId"];
            AnnualEvent currentevent = iaebl.GetActiveEvents().FirstOrDefault();
            string annualeventid = currentevent.ID;

            IEnumerable<ExpertJudge> expertjudges=(from ej in db.ExpertJudges where ej.SubjectID==_subjectid select ej).ToList();

            List<ExpertJudgeDisplayer> ExpertJudges = new List<ExpertJudgeDisplayer>();

            //rebuild score list for excel
            foreach (var rs in expertjudges)
            {
                ExpertJudgeDisplayer ejd = new ExpertJudgeDisplayer()
                {
                     SerialNumber=rs.SerialNumber,
                      RealName=rs.RealName,
                       SubjectName=rs.Subject.Name,
                        Phone=rs.Phone,
                         ContactAddress=rs.ContactAddress,
                          ZipCode=rs.ZipCode
                };
                ExpertJudges.Add(ejd);
            }

            //generate report
            //to use ToReportSource, you must have the class in Dynamic folder
            var report = new DoddleReport.Report(ExpertJudges.ToReportSource());

            //get property info for headertext
            PropertyInfo[] propertyInfos;
            propertyInfos = typeof(AuditWeb.Models.ExpertJudgeDisplayer).GetProperties();

            //hide all columns and set display name for each column if there is a displayname
            foreach (var field in report.DataFields)
            {
                field.Hidden = true;
                try
                {
                    PropertyInfo pi = (from p in propertyInfos where p.Name == field.Name select p).SingleOrDefault();
                    field.HeaderText = Helpers.getDisplayName(pi);
                    field.Hidden = false;
                }
                catch
                {
                }
            }


            //return report. The report format will decided by the url extension name
            //
            // Try the following sample URLs:
            //
            //  http://localhost:X/doddle/ProductReport.html
            //  http://localhost:X/doddle/ProductReport.txt
            //  http://localhost:X/doddle/ProductReport.xls
            //  http://localhost:X/doddle/ProductReport.xlsx (Requires DoddleReport.OpenXml)
            //  http://localhost:X/doddle/ProductReport.pdf (Requires DoddleReport.iTextSharp or DoddleReport.AbcPdf)
            //  
            return new ReportResult(report);
        }

        public ActionResult Archives(string id, string countycode, string archiveid)
        {
            string annualeventid = id;
            if (string.IsNullOrEmpty(id))
                annualeventid = iaebl.GetActiveEvents().FirstOrDefault().ID;

            countycode = countycode == null ? "" : countycode.Trim();
            int _subjectid = (int)HttpContext.Profile["SubjectId"];
            archiveid = archiveid == null ? "" : archiveid.Trim();
            AdminArchiveModel aam = new AdminArchiveModel() { AnnualEventId = annualeventid, CountyCode = countycode, ArchiveId = archiveid, SubjctId = _subjectid, Date = DateTime.Now.Date };

            var archives = iabl.GetArchives(annualeventid, archiveid, _subjectid, countycode);//db.Archives.Include("AnnualEvent").Include("Subject").Include("County").Include("Teacher");
            ViewBag.AnnualEvent = iaebl.GetAnnualEvent(annualeventid);
            ViewBag.AnnualEventId = annualeventid;
            ViewBag.Archives = archives.ToList();
            ViewBag.CountyCode = new SelectList(db.Counties.ToList(), "Code", "Name", countycode);
            ViewBag.SubjectName = db.Subjects.SingleOrDefault(s => s.Id == _subjectid).Name;
            return View(aam);
        }

        public ActionResult Scores()
        {
            AnnualEvent currentevent = iaebl.GetActiveEvents().FirstOrDefault();
            string annualeventid = currentevent.ID;
            int subjectid = (int)HttpContext.Profile["SubjectId"];

            //isbl.GetEventSubjectScores(annualeventid, subjectid);
            ViewBag.AnnualEvent = currentevent;
            ViewBag.AnnualEventId = annualeventid;
            ViewBag.SubjectName = db.Subjects.SingleOrDefault(s => s.Id == subjectid).Name;

            return View(isbl.GetEventSubjectScores(annualeventid, subjectid).ToList());
        }

        public ActionResult ScoreDetails(string id)
        {
            AnnualEvent currentevent = iaebl.GetActiveEvents().FirstOrDefault();
            string annualeventid = currentevent.ID;
            int subjectid = (int)HttpContext.Profile["SubjectId"];
            string archiveid = id;

            ViewBag.AnnualEvent = currentevent;
            ViewBag.AnnualEventId = annualeventid;
            ViewBag.SubjectName = db.Subjects.SingleOrDefault(s => s.Id == subjectid).Name;
            Archive archive = db.Archives.SingleOrDefault(a => a.ID == archiveid);
            ViewBag.Archive = archive;

            return View(isbl.GetArchiveScores(archiveid).ToList());
        }

        public ActionResult DeleteScores(string serialnumber, string archiveid)
        {
            isbl.DeleteScores(serialnumber, archiveid);
            return RedirectToAction("ScoreDetails", new { id=archiveid});
        }

        public ActionResult SingleScoreDetails(string serialnumber, string id)
        {
            AnnualEvent currentevent = iaebl.GetActiveEvents().FirstOrDefault();
            string annualeventid = currentevent.ID;
            int subjectid = (int)HttpContext.Profile["SubjectId"];
            string archiveid = id;

            ViewBag.AnnualEvent = currentevent;
            ViewBag.AnnualEventId = annualeventid;
            ViewBag.SubjectName = db.Subjects.SingleOrDefault(s => s.Id == subjectid).Name;
            Archive archive = db.Archives.SingleOrDefault(a => a.ID == archiveid);
            ViewBag.Archive = archive;

            return View(isbl.GetExpertArchiveScore(serialnumber, archiveid));
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}
